<?php
namespace Frieza\Modules\Decoration\Controllers;

use function Clue\StreamFilter\fun;
use Illuminate\Support\MessageBag;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Doraemon\service\Decoration\Cache as sCache;
use Doraemon\model\Decoration\Category as mCategory;
use Doraemon\model\AdmPush\AdmPushTask as mAdmPushTask;
use Doraemon\model\AdmPush\AdmPushTaskGroup as mAdmPushTaskGroup;
use Encore\Admin\Layout\Row;
use Doraemon\model\Decoration\Adv as mAdv;
use Doraemon\model\Decoration\Subject as mSubject;
use Doraemon\tools\LinkFormat;
use Doraemon\model\Position\PositionBaseInfo;
use Doraemon\tools\ImgUrl;




class MainCategoryController extends Controller
{
    const PAGE_SIZE = 20;


    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
        Admin::script($this->cancelScript(), true);
    }

    public function index(Request $request, Content $content)
    {

        sCache::updateCache();

        $requestParams = $request->all();
        $condition['parent_id'] = 0;
        $condition['ORDER'] = ['sort' => 'DESC'];
        $pageSize = $request->input("per_page", 100);
        $page = $request->input("page", 1);
        $condition['LIMIT'] = [
            ($page - 1) * $pageSize,
            $pageSize
        ];

        $list = mCategory::getAllByWhere($condition);

       $subject_info =  mSubject::getAllByWhere();
       $hash_subject_info = array_combine(array_column($subject_info ,'id') , array_column($subject_info , 'name'));
        $groupList = [];
        if ($list && is_array($list)) {
            foreach ($list as $groupId => $row) {
                $map = [];
                $map['parent_id'] = $row['id'];
                $map['ORDER'] = ['sort' => 'DESC'];
                $group = mCategory::getAllByWhere($map);
                $time = date("Y-m-d H:i:s" ,time());
                foreach($group as &$value){
                    $sql = "select * from `hhz_decoration_adv` where FIND_IN_SET(".$value['id'].",rela_id) and show_type = ".mAdv::SHOW_TYPE_1." AND status =".mAdv::STATUS_OPEN."  and start_time<='".$time."' and end_time>'".$time."'order by sort desc";
                    $adv_info = mAdv::query($sql)->fetchAll();

                    if($adv_info && is_array($adv_info)){
                        foreach($adv_info as $adv){
                            $value['subject_name'][] = [
                                'name' =>  $adv['name'] ? : $hash_subject_info[$adv['sid']],
                                'color'=> $adv['font_color']
                            ];
                        }
                    }

                }
                $row['expand'] = $this->_getExpand($group);
                $groupList[] = $row;
            }
        }
        $gridModel = new pGridDataModel($groupList, $list['total'], [
            'perPage' => $pageSize
        ]);

        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->disablePagination();
                //$grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableCreateButton();
                $grid->disableFilter();
                $grid->tools(function (Grid\Tools $tool) {
                   $tool->append('<div class="pull-right"><div class="btn-group pull-right grid-create-btn" style="margin-right: 10px">
    <a href="/admin/decoration/maincategory/create" class="btn btn-sm btn-success" title="新增分类">
        <i class="fa fa-plus"></i><span class="hidden-xs">&nbsp;&nbsp;新增分类</span>
    </a>
</div></div>');
                });

                $grid->column('title', '一级标题')->expand(function () {
                    return $this->expand;
                }, true);;
                $status = [
                    'on' => [
                        'value' => mCategory::SHOW_OPEN,
                        'text' => '是'
                    ],
                    'off' => [
                        'value' => mCategory::SHOW_CLOSE,
                        'text' => '否'
                    ],
                ];
                $grid->column('is_show', '展示')->switchToggle($status);
                $grid->column('sort', '权重')->editable();

                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableEdit();
                    $actions->disableDelete();
                    $actions->append('&nbsp;&nbsp;<a class="fa fa-edit" href="/admin/decoration/maincategory/create/'.$actions->row->id.'">编辑</a>');
                    $actions->append('&nbsp;&nbsp;<a class="fa fa-trash delcategory" data-id="' . $actions->row->id . '" href="javascript:void(0);">删除</a>');
//

                });
                $grid->footer(function () {
//                    $html = '<span class="help-block"><i class="fa fa-info-circle"></i>&nbsp;注意：排期未锁定，任务状态只有为「已创建任务」的时候，才能排序。如不能排序，可以尝试解锁排期，重置为「已解锁」。</span>';
                   // return $html;
                });
            });
        $tab = new Tab();
        $tab->add('装修分类页', $gridList->render());
        $tab->addLink('轮播banner', url('/admin/decoration/maincategory/banner'));
        $content->row($tab);
        return $content
            ->header('装修分类页')
            ->description(' ')
            ->breadcrumb(['text' => '装修分类页']);
    }

    public function editCategory(Request $request, $categoryId){
        $params = $request->all();
        $params['id'] = $categoryId;
        if($params['is_show']){
            $param = [
                'is_show' => $params['is_show'] == 'on'? 1: 0,
                'admin_id' => Admin::user()->id,
            ];
        }
        if($params['name'] == 'sort'){
            $param = [
                $params['name'] => $params['value'],
                'admin_id' => Admin::user()->id,
                'edit_time' => date("Y-m-d H:i:s" , time())
            ];
        }


        $result = mCategory::updateData($param,['id'=>$params['id']]);
        if($result){
            sCache::updateCache();

            return response()->json([
                'status' => true,
                'message' => "修改成功",
            ]);
        }else{
            return response()->json([
                'status' => false,
                'message' => "修改失败",
            ]);
        }
    }



    private function _getExpand($groupArr)
    {

        $row = new Row();
        if ($groupArr) {
            $GirdModel = new pGridDataModel($groupArr, null, ['pageName' => '']);
            $grid = new Grid($GirdModel);
            $grid->disablePagination();
            $grid->disableCreateButton();
            $grid->disableFilter();
            $grid->disableRowSelector();
            $grid->disableColumnSelector();
            $grid->disableTools();
            $grid->disableExport();
          //  $grid->column('id', '二级分类ID');
            $grid->column('title', '二级标题');
            $status = [
                'on' => [
                    'value' => mCategory::SHOW_OPEN,
                    'text' => '是'
                ],
                'off' => [
                    'value' => mCategory::SHOW_CLOSE,
                    'text' => '否'
                ],
            ];
            $grid->column('is_show', '展示')->switchToggle($status);
            $grid->column('sort','权重')->editable();
            $grid->column('rela_tag', '关联主题')->display(function() {
                $options='';
                if ($this->subject_name) {
                    foreach ($this->subject_name as $value) {
                        $backgroud = '';
                        if($value['color']){
                            $backgroud = $value['color'];
                        }
                        $options = $options . '<button style="display:inline-block;margin:2px;background:'.$backgroud.';" class="marktag btn btn-sm" data-had="">'.$value['name'].'</button>';
                    }
                }
                return $options;
            })->style("width:200px");

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableEdit();
                $actions->disableDelete();
//                $actions->append('<a href="/admin/decoration/maincategory/subjectlist/' . $actions->row->id.'" class="fa fa-info-circle">查看关联主题</a>');

                    $actions->append('&nbsp;&nbsp;<a class="fa fa-edit" data-id="' . $actions->row->id . '" href="/admin/decoration/maincategory/create/'.$actions->row->id.'">编辑</a>');
                $actions->append('&nbsp;&nbsp;<a class="fa fa-trash delcategory" data-id="' . $actions->row->id . '" href="javascript:void(0);">删除</a>');

            });
            $grid->disablePagination();
            $row->column('12', $grid);
            return $row->render();
        }
        return '';

    }





    public function getSubjectList(Request $request, Content $content,  $rela_id =0 ){
        //列表获取搜索条件
        $get = $_SERVER["QUERY_STRING"]?'?'.$_SERVER["QUERY_STRING"]:'';

        $params = $request->all();
        //筛选状态status
        $map_status = [];
        if(empty($params['status'])){
            $map_status = [mAdv::STATUS_OPEN];
        }else{
            $map_status = [$params['status']];
        }
        if($rela_id>0){
            $sql = 'select * from `hhz_decoration_adv` where FIND_IN_SET('.$rela_id.',rela_id) and show_type = '.mAdv::SHOW_TYPE_1.' AND status in ('.implode("," , $map_status).')  order by sort desc';
            $adv_info = mAdv::query($sql)->fetchAll();
        }
        $rela_info = mCategory::getOneByWhere(['id' =>$rela_id]);
        if($rela_info && is_array($rela_info)){
            $rela_name = $rela_info['title'];
            $parent_id = $rela_info['parent_id'];
        }
        if($adv_info && is_array($adv_info)){
            $subject_ids = array_filter(array_column($adv_info,'sid')) ?:[];
           $subject_info =  mSubject::getAllByWhere(['id'=>$subject_ids ]);
           $hash_subject = [];
           if($subject_info && is_array($subject_info)){
               $hash_subject = array_combine(array_column($subject_info,'id') , $subject_info);
           }
            foreach($adv_info as &$value){
                $value['rela_name'] = $rela_name;
                $value['parent_id'] = $parent_id;
                if(isset($hash_subject[$value['sid']])){
                    $value['sid_name'] = $hash_subject[$value['sid']]['name'];
                }
                $value['url'] = LinkFormat::generateLink($value['link_type'] ,$value['link_params'])['app_template'];
            }
        }
        $gridModel = new pGridDataModel($adv_info, count($adv_info), [
            'perPage' => self::PAGE_SIZE
        ]);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) use ($get,$rela_id,$parent_id){
            $grid->disableExport();
            $grid->disableRowSelector();
           $grid->disableCreateButton();
            $grid->expandFilter();
            $grid->disablePagination();



            $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();
                    $filter->column(1 / 2, function ($filter) {
                        $filter->between('date_time', '展示时间')->datetime()->condition($_GET);
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('status', '状态')->select(MainAdvController::STATUS_ARRAY_SELECT)->default(mAdv::STATUS_OPEN);
                    });
                });
            $grid->tools(function (Grid\Tools $tool)use($rela_id,$parent_id) {

                $tool->append('<div class="pull-right"><div class="btn-group pull-right grid-create-btn" style="margin-right: 10px">
    <a href="/admin/decoration/mainadv/content/create/'.$parent_id.'/'.$rela_id.'/0/0/'.mAdv::SHOW_TYPE_1.'" class="btn btn-sm btn-success" title="新增">
        <i class="fa fa-plus"></i><span class="hidden-xs">&nbsp;&nbsp;新增</span>
    </a>
</div></div>');
            });
                $grid->fixColumns(0, -1);


            $grid->column('id')->sort();
            $grid->column('rela_name', '卡片信息')->display(function () {

                $display[] ="<sapn style='font-size: 10px'>分类信息:<b>".$this->rela_name."</b></sapn>" ;
                $display[] ="<sapn style='font-size: 10px'>关联主题:<b>" .$this->sid_name."</b></sapn>";
                if(!empty($this->name) || $this->name == '') {
                    $display[]= '<p style="color:' . $this->font_color . ';">名称:' . $this->name . '</p>';
                }else{
                    $display[]= '<p style="color:' . $this->font_color . ';">名称:暂空</p>';
                }
                return implode('<br/>', $display);
            });
            $grid->column('sort', '排序');
            $grid->column('status', '展示状态')->display(function(){
                $color='';
                switch ($this->status){
                    case 0:$st = '未生效'; $color="deeppink";break;
                    case 1:$st = '开启';$color="green";break;
                    case 2:$st = '已失效';$color="red";break;break;
                }
                return '<p style="color:'.$color.';">'.$st.'</p>';

            });

            $grid->column('url', '链接信息')->display(function (){
                return "<span>".$this->url."</span>";
            });

            $grid->column('start_time', '展示时间')->display(function() {
                return '开始时间：'.$this->start_time." ~ ".'结束时间：'.$this->end_time;
            });;
            $grid->column('admin_id', '操作人')->display(function(){
                if(!$this->admin_id) {
                    return '暂无';
                }else{
                    return Admin::user()->find($this->admin_id)->name;
                }
            });
            $grid->column('edit_time', '更新时间');


            $grid->actions(function (Grid\Displayers\Actions $actions) use($get,$rela_id){
                $actions->disableView();
                $actions->disableEdit();
                $actions->disableDelete();

                if($actions->row->status >= 2) {
                    $actions->disableEdit();
                }
                $actions->append('&nbsp;&nbsp;<a class="fa fa-edit"  href="/admin/decoration/mainadv/content/create/'.$actions->row->parent_id.'/'.$rela_id.'/0/'.$actions->row->id.'/'.mAdv::SHOW_TYPE_1.'/edit">编辑</a>');
                $actions->append('&nbsp;&nbsp;<a class="fa fa-trash	delcontent" data-id="' . $actions->row->id . '" data-rela-id="' . $rela_id . '" href="javascript:void(0);">删除</a>');


            });

        });
        $list = $listGrid->render();
        return $content
            ->header('装修分类页')
            ->breadcrumb(
                ['text' => '装修分类页', 'url' => '/decoration/maincategory'],
                ['text' => '关联主题', 'url' => '/decoration/maincategory/subjectlist/'.$rela_id]
            )
            ->body($list);
    }


    public function getBanner(Request $request , Content $content)
    {

        $show_type = mAdv::SHOW_TYPE_2;
        $map = [];

        $start_time =  date("Y-m-d H:i:s" ,time());
        $end_time = date("Y-m-d H:i:s" ,time());
        if($show_type>0) {
            $map['AND']['show_type'] = $show_type;
        }

        if(empty($map['AND'])){
            unset($map['AND']);
        }
        $map['AND']['status'] = mAdv::STATUS_OPEN;


        $map['ORDER'] = ['id' => 'DESC'];

        $data = mAdv::getAllByWhere($map);


        $gridModel = new pGridDataModel($data, count($data), [
            'perPage' => self::PAGE_SIZE
        ]);
       // dump($data);die();

        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            $grid->disableFilter();
            $grid->tools(function (Grid\Tools $tool) {
                $tool->append('<div class="pull-right"><div class="btn-group pull-right grid-create-btn" style="margin-right: 10px">
    <a href="/admin/decoration/maincategory/banner/create" class="btn btn-sm btn-success" title="新增">
        <i class="fa fa-plus"></i><span class="hidden-xs">&nbsp;&nbsp;新增</span>
    </a>
</div></div>');
            });
            $grid->column('id');
            $grid->column('pic_id_url', '封面')->display(function(){
                if(!empty($this->pic_id_url)) {
                    return '<img style="width:150px;height:100px" src="' . $this->pic_id_url . '" >';
                }
            });
            $grid->column('pos', '轮播位置');
            $grid->column('link', '链接信息')->linkSelect()->width(4,2);
            $grid->column('start_time', '展示时间')->display(function() {
                return '开始时间：'.$this->start_time." ~ ".'结束时间：'.$this->end_time;
            });

            $grid->column('status', '状态')->display(function(){
                switch ($this->status){
                    case 0:$st = '未生效';break;
                    case 1:$st = '开启';break;
                    case 2:$st = '已失效';break;break;
                }
                return $st;
            });

            $grid->actions(function (Grid\Displayers\Actions $actions){
                //  $actions->disableView();
                $actions->disableDelete();
                $actions->disableEdit();
                $actions->append('&nbsp;&nbsp;<a class="fa fa-edit"  href="/admin/decoration/maincategory/banner/create/'.$actions->row->id.'">编辑</a>');
                $actions->append('&nbsp;&nbsp;<a class="fa fa-trash	delbanner" data-id="' . $actions->row->id . '"  href="javascript:void(0);">删除</a>');
            });

        });
        $list = $listGrid->render();
        //$list = $this->_bannerlist($map , $show_type);
        $tab = new Tab();
        $tab->addLink('装修分类页', url('admin/decoration/maincategory'));
        $tab->add('轮播banner', $list,true);
        $content
            ->header('装修-[干货]装修主题页-顶部轮播banner')
            ->breadcrumb(['text' => '轮播banner', 'url' => '/decoration/maincategory/banner']);
        return $content->body($tab);
    }




    //获取广告位
    public function _bannerlist($request, $showType = 0){
        $start_time =  date("Y-m-d H:i:s" ,time());
        $end_time = date("Y-m-d H:i:s" ,time());
        if($showType>0) {
            $request['AND']['show_type'] = $showType;
        }
        if(empty($request['AND'])){
            unset($request['AND']);
        }
        $request['AND']['start_time[<=]'] = $start_time;
        $request['AND']['end_time[>]'] = $end_time;


        $request['ORDER'] = ['pos' => 'ASC'];
        $count = mAdv::getCount($request);
        $data = mAdv::getAllByWhere($request);
        $gridModel = new pGridDataModel($data, $count, [
            'perPage' => self::PAGE_SIZE
        ]);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            $grid->disableFilter();
            $grid->tools(function (Grid\Tools $tool) {
                $tool->append('<div class="pull-right"><div class="btn-group pull-right grid-create-btn" style="margin-right: 10px">
    <a href="/admin/decoration/maincategory/banner/create" class="btn btn-sm btn-success" title="新增">
        <i class="fa fa-plus"></i><span class="hidden-xs">&nbsp;&nbsp;新增</span>
    </a>
</div></div>');
            });
            $grid->column('id')->sort();
            $grid->column('pic_id_url', '封面')->display(function(){
                if(!empty($this->pic_id_url)) {
                    return '<img style="width:150px;height:100px" src="' . $this->pic_id_url . '" >';
                }
            });
            $grid->column('pos', '轮播位置');
            $grid->column('link', '链接信息')->linkSelect()->width(4,2);
            $grid->column('start_time', '展示时间')->display(function() {
                return '开始时间：'.$this->start_time." ~ ".'结束时间：'.$this->end_time;
            });

            $grid->column('status', '状态')->display(function(){
                switch ($this->status){
                    case 0:$st = '未生效';break;
                    case 1:$st = '开启';break;
                    case 2:$st = '已失效';break;break;
                }
                return $st;
            });

            $grid->actions(function (Grid\Displayers\Actions $actions){
                //  $actions->disableView();
                $actions->disableDelete();
                $actions->disableEdit();
                $actions->append('&nbsp;&nbsp;<a class="fa fa-edit"  href="/admin/decoration/maincategory/banner/create/'.$actions->row->id.'">编辑</a>');
                $actions->append('&nbsp;&nbsp;<a class="fa fa-trash	delcontent" data-id="' . $actions->row->id . '" data-rela-id="' . $rela_id . '" href="javascript:void(0);">取消关联</a>');
            });

        });
        $list = $listGrid->render();
        return $list;
    }









    public function sort(Request $request)
    {
        $params = $request->all();
        if($params['sort'] && is_array($params['sort'])){
            $params['sort']  = array_values(array_reverse(array_flip($params['sort'])));
        }


        $result = mCategory::action(function()use($params){
            foreach($params['sort'] as $_k=>$id){
                if(!mAdv::updateData(['sort' => $_k], ['id' => $id])){
                    return false;
                }
            }
            return true;
        });
        if($result){
//          sCache::updateCache();
            return response()->json([
                'status' => true,
                'message' => "操作成功",
            ]);
        }else{
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
    }




    private function cancelScript()
    {
        return <<<SCRIPT
        $('.cancel-push').unbind('click').click(function(){
            var id= $(this).data('id');
            layer.confirm('确定要取消任务 '+id+' 吗？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                let url = '/admin/push/task/' +  id  + '/cancel';
                let params = {};
                $.post(url, params , function (result) {
                    if (result.code == 1) {
                        layer.msg(result.title);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.msg);
                    }
                });
            });
        })
        $('.delcontent').unbind('click').click(function(){
            var id= $(this).data('id');
           var sid = $(this).data('rela-id');
            layer.confirm('确定要删除么？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                 let url = '/admin/decoration/mainadv/subjectdel/' +  sid + '/' + id;
                let params = {};
                $.post(url, params , function (result) {
                    if (result.code == 1) {
                        layer.msg(result.title);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.msg);
                    }
                });
            });
        })
        
         $('.delbanner').unbind('click').click(function(){
            var id= $(this).data('id');
            layer.confirm('确定要删除么？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                 let url = '/admin/decoration/maincategory/bannerdel/'+ id;
                let params = {};
                $.post(url, params , function (result) {
                    if (result.code == 1) {
                        layer.msg(result.title);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.msg);
                    }
                });
            });
        })
        
          $('.delcategory').unbind('click').click(function(){
            var id= $(this).data('id');
            layer.confirm('确定要删除么？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                 let url = '/admin/decoration/maincategory/del/'  + id;
                let params = {};
                $.post(url, params , function (result) {
                    if (result.code == 1) {
                        layer.msg(result.title);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.msg);
                    }
                });
            });
        })
        function closeLayer() {
            var index = parent.layer.getFrameIndex(window.name);
            parent.layer.close(index);
        }
        $('.cancel-group').unbind('click').click(function(){
            var id= $(this).data('id');
            var group_time=$(this).data('time');
            layer.confirm('确定要取消「'+group_time+'」的排期吗？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                let url = '/admin/push/task/' +  id  + '/cancelGroup';
                let params = {};
                $.post(url, params , function (result) {
                    if (result.code == 1) {
                        layer.msg(result.title);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.msg);
                    }
                });
            });
        })
        $('.unlock-group').unbind('click').click(function(){
            var id= $(this).data('id');
            var group_time=$(this).data('time');
            layer.confirm('确定要解除锁定的「'+group_time+'」排期吗？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                let url = '/admin/push/task/' +  id  + '/unlockGroup';
                let params = {};
                $.post(url, params , function (result) {
                    if (result.code == 1) {
                        layer.msg(result.title);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.msg);
                    }
                });
            });
        })
        $('.lock-group').unbind('click').click(function(){
            var id= $(this).data('id');
            var group_time=$(this).data('time');
            layer.confirm('确定要锁定「'+group_time+'」排期吗？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                let url = '/admin/push/task/' +  id  + '/lockGroup';
                let params = {};
                $.post(url, params , function (result) {
                    if (result.code == 1) {
                        layer.msg(result.title);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.msg);
                    }
                });
            });
        });
SCRIPT;
    }


    public function edit(Request $request,Content $content, $parentId = 0, $sonId = 0){

        $requests = $request->all();
        $requests['parent_id'] = $parentId;
        $requests['id'] = $sonId;
     //   $requests = self::_filterWhere($requests);
        $requests = $request;

        $tab = new Tab();
            $tab->add('基本信息', self::editAction($requests, strpos($request->url(), 'create')));
        if(!strpos($request->url(), 'create')) {
            if($sonId > 0) {
                $tab->addLink('主题列表', '/admin/decoration/category/'.$parentId.'/edit/'.$sonId.'/edit/subject');
            }else{
                $tab->add('子分类列表', self::listAction($requests));
                $tab->addLink('资源位列表', '/admin/decoration/category/'.$parentId.'/edit/'.$sonId.'/edit/adv');
            }
        }
        $curUrl = '';
        if($sonId > 0) {
            return $content
                ->header('分类编辑')
                ->breadcrumb(
                    ['text' => '一级分类', 'url' => '/decoration/category'],
                    //['text' => '二级分类', 'url' => $request->url()],
                    ['text' => '分类编辑', 'url' => '/decoration/category/create']
                )
                ->body($tab);
        }else{
            return $content
                ->header('分类编辑')
                ->breadcrumb(
                    ['text' => '一级分类', 'url' => '/decoration/category'],
                    ['text' => '分类编辑', 'url' => '/decoration/category/create']
                )
                ->body($tab);
        }
    }

    public function create(Request $request ,Content $content,$categoryid = 0 )
    {
        $data = [];
        if($categoryid>0){
            $data=mCategory::getOneByWhere(['id'=>$categoryid]);
            $data['is_first'] = $data['parent_id'] == 0? 1: 0;
        }
        $category = mCategory::getAllByWhere(['parent_id' =>0, 'status' => mCategory::STATUS_OPEN], ['id', 'title']);

        $categorys = [];
        if (!empty($category)) {
            foreach ($category as &$_v) {
                $categorys[$_v['id']] = $_v['title'];
            }
        }
        //获取所有分组
        $form = new Form($data);
        $form->hidden('id');
        $form->fieldChange('is_first', '一级标题', $form)
            ->options([ 0 => '否',1 => '是'])
            ->default(0)
            ->callablePreCommon(function (Form $form) use($categorys){
            })->callableMap([
                0  => function (Form $form)use($categorys) {
                    $form->select('parent_id', '上级分类')
                        ->options($categorys)->required();
                },
                1=>function (Form $form){}
                ]);
        $form->text('title', '标题')->required('不能为空');
        $form->radio('is_show', '是否显示')
            ->options([0=>'否', 1=>'是'])->setWidth(4, 2);
        $form->number("sort",'权重');
        $form->action('/admin/decoration/maincategory/save');
        $list =  $form->render();
        $tab = new Tab();
        if($categoryid){
            $tab->add("编辑分类" ,$list , true);
            if($data['is_first'] == 0){
                $tab->addLink("编辑关联主题" ,"/admin/decoration/maincategory/getsubject/".$categoryid,false);
            }

            $content->breadcrumb(
                ['text' => '装修分类页', 'url' => '/decoration/maincategory'],
                ['text' => '编辑-分类页', 'url' => '/decoration/maincategory/create/'.$categoryid]);
        }else{
            $tab->add("新增分类" ,$list);
            $content->breadcrumb(
                ['text' => '装修分类页', 'url' => '/decoration/maincategory'],
                ['text' => '新增-分类页', 'url' => '/decoration/maincategory/create/'.$categoryid]);

        }

        return $content->body($tab);
    }

    //
    public function save(Request $request , Content $content ,$id = 0)
    {
        $params = $request->all();

        $data = [];
        if($id){
            $text_id = $id;
            if(isset($params['is_show'])){
                $data['is_show'] =    $params['is_show']  == "on" ? 1 : 0;
            }
            if($params['name'] == "sort"){
                $data['sort'] = $params['value'];
            }

        }else{
            $id = $params['id'] ? : 0;

            if($params['is_first'] == 0 ){
                $data['parent_id'] = $params['parent_id'];

            }else{
                $data['parent_id'] = 0;

            }
            $data['title'] = $params['title']  ? : '';
            $data['is_show'] = $params['is_show'];
            $data['sort']  = $params['sort'] ? : 0;
        }


        if($id){
            $data['add_time'] = date("Y-m-d H:i:s" ,time());
            $result =  mCategory::updateData($data,['id' => $id]);
        }else{
            $data['status'] = mSubject::STATUS_OPEN;
            $data['admin_id'] =  Admin::user()->id;
            $data['add_time'] = date("Y-m-d H:i:s" ,time());
            $result =  mCategory::addData($data);
        }
        if($result){
            $success = new MessageBag([
                'title' => '操作成功'
            ]);
            if($text_id){
                return response()->json([
                    'status' => true,
                    'message' => "操作成功",
                ]);

            }
            if($id> 0){
                $preurl = '/admin/decoration/maincategory/create/'.$id;
            }else{
                $preurl  ='admin/decoration/maincategory';
            }

            sCache::updateCache();
            return redirect($preurl)->with(compact('success'));
        }else{
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
    }


    //

    public function SubjectList(Request $request , Content $content,$rela_id = 0)
    {
        if($rela_id>0){
        $sql = 'select * from `hhz_decoration_adv` where FIND_IN_SET('.$rela_id.',rela_id) and show_type = '.mAdv::SHOW_TYPE_1.' AND status in ('.implode("," , [mAdv::STATUS_OPEN]).')  order by sort desc';
        $adv_info = mAdv::query($sql)->fetchAll();
        }
        $rela_info = mCategory::getOneByWhere(['id' =>$rela_id]);
        if($rela_info && is_array($rela_info)){
            $rela_name = $rela_info['title'];
            $parent_id = $rela_info['parent_id'];
        }
        if($adv_info && is_array($adv_info)){
            $subject_ids = array_filter(array_column($adv_info,'sid')) ?:[];
            $subject_info =  mSubject::getAllByWhere(['id'=>$subject_ids ]);
            $hash_subject = [];
            if($subject_info && is_array($subject_info)){
                $hash_subject = array_combine(array_column($subject_info,'id') , $subject_info);
            }
            foreach($adv_info as &$value){
                $value['rela_name'] = $rela_name;
                $value['parent_id'] = $parent_id;
                if(isset($hash_subject[$value['sid']])){
                    $value['sid_name'] = $hash_subject[$value['sid']]['name'];
                }
                $value['url'] = LinkFormat::generateLink($value['link_type'] ,$value['link_params'])['app_template'];
            }
        }
        $gridModel = new pGridDataModel($adv_info, count($adv_info), [
            'perPage' => self::PAGE_SIZE
        ]);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) use ($get,$rela_id,$parent_id){
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            $grid->disableFilter();
            $grid->disablePagination();

            $grid->tools(function (Grid\Tools $tool)use($rela_id,$parent_id) {

                $tool->append('<div class="pull-right"><div class="btn-group pull-right grid-create-btn" style="margin-right: 10px">
    <a href="/admin/decoration/maincategory/subject/create/'.$rela_id.'" class="btn btn-sm btn-success" title="新增">
        <i class="fa fa-plus"></i><span class="hidden-xs">&nbsp;&nbsp;新增</span>
    </a>
</div></div>');
            });
            $grid->fixColumns(0, -1);


            $grid->column('id')->sort();
            $grid->column('rela_name', '卡片信息')->display(function () {

                $display[] ="<sapn style='font-size: 10px'>分类信息:<b>".$this->rela_name."</b></sapn>" ;
                $display[] ="<sapn style='font-size: 10px'>关联主题:<b>" .$this->sid_name."</b></sapn>";
                return implode('<br/>', $display);
            });
            $grid->column('sort', '排序');
            $grid->column('font_color', '背景颜色')->display(function(){
                $name = $this->sid_name;
                if($this->name){
                    $name=$this->name;
                }
                return '<p style="background-color: '.$this->font_color.';color:'.$this->info_color.';width: 50px; display: block">'.$name.'</p>';
            });

            $grid->column('url', '链接信息')->display(function (){
                return "<span>".$this->url."</span>";
            });
            $grid->column('start_time', '展示时间')->display(function() {
                return '开始时间：'.$this->start_time." ~ ".'结束时间：'.$this->end_time;
            });


            $grid->actions(function (Grid\Displayers\Actions $actions) use($get,$rela_id){
                $actions->disableView();
                $actions->disableEdit();
                $actions->disableDelete();

                if($actions->row->status >= 2) {
                    $actions->disableEdit();
                }
                $actions->append('&nbsp;&nbsp;<a class="fa fa-edit"  href="/admin/decoration/maincategory/subject/create/'.$rela_id.'/'.$actions->row->id.'">编辑</a>');
                $actions->append('&nbsp;&nbsp;<a class="fa fa-trash	delcontent" data-id="' . $actions->row->id . '" data-rela-id="' . $rela_id . '" href="javascript:void(0);">取消关联</a>');


            });

        });
        $list = $listGrid->render();
        $tab = new Tab();
        $tab->addLink("编辑分类" ,'/admin/decoration/maincategory/create/'.$rela_id);

        $tab->add("编辑关联主题" ,$list ,true) ;
        $content->breadcrumb(
            ['text' => '装修分类页', 'url' => '/decoration/maincategory'],
            ['text' => '编辑-关联主题页', 'url' => '/decoration/maincategory/create/'.$rela_id]);

        return $content->body($tab);
    }



    //edit subject
    public  function createSubject(Request $request ,Content $content , $rela_id = 0 , $id = 0)
    {
        $info = [];
        $category = mCategory::getOneByWhere(['id'=>$rela_id]);
        if($id){
            $info = mAdv::getOneByWhere(['id'=>$id]);
            $info['is_subject'] = $info['sid'] ? 1 :2;
            $info['link'] = [
                'link_type'=> $info['link_type'],
                'link_params'=> $info['link_params'],
            ];
        }
        $subject = mSubject::getAllByWhere(['status'=>mSubject::STATUS_OPEN],['id','name']);
        $hash_subject = array_combine(array_column($subject ,'id') , array_column($subject, 'name'));
        $form =new Form($info);
        //获取所有分组
        $form->hidden('id');
        $form->hidden('rela_id');
        $form->fieldChange('is_subject', '是否主题', $form)
            ->options([ 1 => '是',2 => '否'])
            ->default(1)
            ->callablePreCommon(function (Form $form) use($hash_subject){
            })->callableMap([
                1  => function (Form $form)use($hash_subject) {
                    $form->select('sid', '主题')
                        ->options($hash_subject)->required();
                },
                2=>function (Form $form){
                    $form->linkSelect('link','跳转');
                }
                ]);
        $form->text('name', '名称')->help("可重命名 主题名");
        $form->color('font_color', '字体背景色')->setWidth(4, 2);
        $form->datetimeRange('start_time', 'end_time', '有效期限:开始-结束')->required('不能为空');
        $form->number("sort",'权重');
        $form->action('/admin/decoration/maincategory/save/subject/'.$rela_id);
        $list =  $form->render();
        $content->breadcrumb(
            ['text' => '装修分类页', 'url' => '/decoration/maincategory'],
            ['text' => '编辑-关联主题', 'url' => '/decoration/maincategory/getsubject/'.$rela_id],
            ['text' => '新增-关联主题', 'url' => '/decoration/maincategory/subject/create/'.$rela_id]);
        return $content->body($list);
    }

    //save link

    public function saveSubject(Request $request , Content $content , $category_id = 0)
    {
        $params = $request->all();
        $data = [];
        $id = $params['id'] ? : 0;
        if($params['rela_id']){
            $data['rela_id'] = $params['rela_id'];
        }else{
            $data['rela_id'] = $category_id;
        }
        if($params['is_subject'] == 1 ){
            $data['sid'] = $params['sid'];
            $data['link_type'] = 'hhz://decorate_tag';
            $data['link_params']  ='{"decorate_tag":"'.$params['sid'].'"}';
        }else{
            $data['link_type'] = $params['link_type'];
            $data['link_params'] = json_encode($params['link_params']);

        }
        $data['name'] = $params['name']  ? : '';
        if($params['start_time'] && $params['end_time']){
            $data['start_time'] = $params['start_time'];
            $data['end_time'] = $params['end_time'];
        }
        $data['sort']  = $params['sort'] ? : 0;
        $data['font_color'] = $params['font_color'] ? : '';
        if($id){
            $data['edit_time'] = date("Y-m-d H:i:s" ,time());
           $result =  mAdv::updateData($data,['id' => $id]);
        }else{
            $data['status'] = mAdv::STATUS_OPEN;
            $data['admin_id'] =  Admin::user()->id;
            $data['show_type'] = mAdv::SHOW_TYPE_1;
            $data['add_time'] = date("Y-m-d H:i:s" ,time());

           $result =  mAdv::addData($data);
        }
        if($result){
            sCache::updateCache();

            $success = new MessageBag([
                'title' => '操作成功'
            ]);

            return redirect('/admin/decoration/maincategory/getsubject/'.$category_id)->with(compact('success'));
        }else{
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }

    }


    //删除分类
    public function delcategory(Request $request , Content $content ,$id)
    {
        $data = [
            'admin_id'=>Admin::user()->id,
            'edit_time'=>date("Y-m-d H:i:s" , time()),
            'status' => mCategory::STATUS_DELETE
        ];


        $result = mCategory::updateData($data, ['id'=>$id]);

        if($result){
            sCache::updateCache();
            $success = [
                'title' =>  ' 更新成功',
                'code' => 1,
            ];


        }else{
            return response()->json([
                'status' => true,
                'message' => "操作成功",
            ]);

        }
        return response()->json($success);

    }

    //banner create
    public function createBanner(Request $request ,Content $content,$id = 0 )
    {
        $info = [];
        if($id){
            $info = mAdv::getOneByWhere(['id'=>$id]);
            $info['link'] = [
                'link_type'=> $info['link_type'],
                'link_params'=> $info['link_params'],
            ];
        }
        $form =new Form($info);
        //获取所有分组
        $form->hidden('id');
        $form->imgUpload('pic_id', '封面');
        $form->linkSelect('link','跳转');

        $form->datetimeRange('start_time', 'end_time', '有效期限:开始-结束')->required('不能为空');
        $form->number("pos",'位置');
        $form->action('/admin/decoration/maincategory/banner/save');
        $list =  $form->render();
        $content->breadcrumb(
            ['text' => '装修分类页', 'url' => '/decoration/maincategory'],
            ['text' => '轮播banner', 'url' => 'decoration/maincategory/banner'],
            ['text' => '新增', 'url' => '/decoration/maincategory/banner/create']);
        return $content->body($list);
    }

    //save banner

    public function saveBanner(Request $request , Content $content ,$id = 0)
    {
        $params = $request->all();

        $data = [];
        if($id == 0){
            $id = $params['id'] ? : 0;
        }


        $data['link_type'] = $params['link_type'];
        $data['link_params'] = json_encode($params['link_params'] , true);
        if($params['pic_id']){
            $data['pic_id'] = $params['pic_id'] ? : '';
        }
        if($params['start_time'] && $params['end_time']){
            $data['start_time'] = $params['start_time'];
            $data['end_time'] = $params['end_time'];
        }
        if($params['pos']){
            $data['pos']  = $params['pos'] ? : 0;
        }
        if($id){
            $data['edit_time'] = date("Y-m-d H:i:s" ,time());
            $result =  mAdv::updateData($data,['id' => $id]);
        }else{
            $data['status'] = mAdv::STATUS_OPEN;
            $data['admin_id'] =  Admin::user()->id;
            $data['show_type'] = mAdv::SHOW_TYPE_2;
            $data['add_time'] = date("Y-m-d H:i:s" ,time());

            $result =  mAdv::addData($data);
        }
        if($result){
            sCache::updateCache();
            $success = new MessageBag([
                'title' => '操作成功'
            ]);

            return redirect('/admin/decoration/maincategory/banner')->with(compact('success'));
        }else{
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }

    }

    public function sortbanner(Request $request)
    {
        $params = $request->all();

        $result = mCategory::action(function()use($params){
            foreach($params['sort'] as $_k=>$_v){
                if(!mAdv::updateData(['pos' => $_v], ['id' => $_k])){
                    return false;
                }
            }
            return true;
        });
        if($result){
        sCache::updateCache();
            return response()->json([
                'status' => true,
                'message' => "操作成功",
            ]);
        }else{
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
    }

    //删除分类
    public function delbanner(Request $request , Content $content ,$id)
    {
        $data = [
            'admin_id'=>Admin::user()->id,
            'edit_time'=>date("Y-m-d H:i:s" , time()),
            'status' => mAdv::STATUS_DELETE
        ];


        $result = mAdv::updateData($data, ['id'=>$id]);

        if($result){
            sCache::updateCache();

            $success = [
                'title' =>  ' 更新成功',
                'code' => 1,
            ];
        }else{
            return response()->json([
                'status' => true,
                'message' => "操作成功",
            ]);

        }
        return response()->json($success);

    }


    //更新缓存
    public function  updateCache()
    {
        sCache::updateCache();

    }
















}